package com.alex.zookeeper.service.configuration;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 实现更新配置：在一些随机时刻更新配置数据的引用
 */
@Slf4j
public class ConfigUpdater {

    public static final String PATH = "/config";

    private ActiveKeyValueStore store;

    private Random random = new Random();

    public ConfigUpdater() throws IOException, InterruptedException {
        store = new ActiveKeyValueStore();
        store.connection();
    }

    public void run() throws KeeperException, InterruptedException {
        while (true) {
            String value = random.nextInt(100) + "";
            store.write(PATH, value);
            log.info("Set {} to {}", PATH, value);
            TimeUnit.SECONDS.sleep(random.nextInt(10));
        }
    }

    public static void main(String... args) throws IOException, InterruptedException, KeeperException {
        ConfigUpdater configUpdater = new ConfigUpdater();
        configUpdater.run();
    }
}
